<template>
    <div>
        <el-drawer v-model="visible" title="创建直播计划" direction="rtl" size="40%" :before-close="handleClose">
            <div class="create-live-drawer">
                <el-steps :active="step" finish-status="success" align-center>
                    <el-step title="基本信息" />
                    <el-step title="提交审核" />
                    <el-step title="完成" />
                </el-steps>

                <!-- 步骤1：基本信息 -->
                <div v-if="step === 1" class="step-form">
                    <div class="live-type-switch">
                        <div class="switch-item" :class="{ active: liveType === 'live' }"
                            @click="toggleLiveType('live')">
                            <span>直播</span>
                        </div>
                        <div class="switch-item" :class="{ active: liveType === 'vod' }" @click="toggleLiveType('vod')">
                            <span>点播</span>
                        </div>
                    </div>
                    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" label-position="top">
                        <el-form-item label="直播标题" prop="title" :required="false">
                            <template #label>
                                <span>直播标题<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-input v-model="form.title" maxlength="15" show-word-limit placeholder="请输入" />
                        </el-form-item>

                        <el-form-item label="开播时间" prop="startTime" :required="false">
                            <template #label>
                                <span>开播时间<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开播时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;"
                                :disabled-date="disabledDate" :disabled-time="disabledTime" @change="validateTime" />
                            <div v-if="timeError" class="el-form-item__error">{{ timeError }}</div>
                        </el-form-item>
                        <el-form-item label="结束时间" prop="endTime" :required="false">
                            <template #label>
                                <span>结束时间<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择开播时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;"
                                :disabled-date="disabledDate" :disabled-time="disabledTime"  />
                            <div v-if="timeError" class="el-form-item__error">{{ timeError }}</div>
                        </el-form-item>

                        <el-form-item label="直播封面" prop="cover" :required="false">
                            <template #label>
                                <span>直播封面<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-upload class="cover-uploader" :show-file-list="false" :before-upload="beforeCoverUpload"
                                :http-request="uploadAvatar">
                                <img v-if="form.cover" :src="form.cover" class="cover" />
                                <div v-else class="cover-placeholder">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                    <span>上传</span>
                                </div>
                            </el-upload>
                        </el-form-item>

                        <el-form-item v-if="liveType === 'vod'" label="点播视频" prop="vodVideo" :required="false">
                            <template #label>
                                <span>点播视频<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-upload class="cover-uploader" :show-file-list="false" :before-upload="beforeVodUpload"
                                :http-request="uploadAvatar2">
                                <video v-if="form.vodVideo" :src="form.vodVideo" class="cover"
                                    @click.stop="videoPreviewVisible = true" />
                                <div v-else class="cover-placeholder">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                    <span>上传</span>
                                </div>
                            </el-upload>
                        </el-form-item>

                        <el-dialog v-model="videoPreviewVisible" width="60%" center custom-class="no-bg-dialog">
                            <video :src="form.vodVideo" controls style="width: 100%; height: auto;" />
                        </el-dialog>

                        <el-form-item v-if="liveType === 'vod'">
                            <template #label>
                                <span>是否横屏<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-switch v-model="form.isHorizontal" :active-value="true" :inactive-value="false" />
                        </el-form-item>

                        <el-form-item label="直播介绍" prop="desc" :required="false">
                            <template #label>
                                <span>直播介绍<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-input v-model="form.desc" type="textarea" maxlength="100" show-word-limit :rows="4"
                                placeholder="请输入直播的相关介绍" />
                        </el-form-item>

                        <el-form-item label="电话客服" prop="phone" :required="false">
                            <template #label>
                                <span>电话客服<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-input v-model="form.phone" placeholder="请输入电话号码" />
                        </el-form-item>

                        <el-form-item label="企业微信客服" prop="wxQr" :required="false">
                            <template #label>
                                <span>企业微信客服<span style="color: #f56c6c;font-weight: 700;">*</span></span>
                            </template>
                            <el-upload class="qr-uploader" :show-file-list="false" :before-upload="beforeQrUpload"
                                :http-request="uploadAvatar3">
                                <img v-if="form.wxQr" :src="form.wxQr" class="qr" />
                                <div v-else class="qr-placeholder">
                                    <el-icon>
                                        <Plus />
                                    </el-icon>
                                    <span>上传</span>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 步骤2：提交审核 -->
                <div v-if="step === 2" class="step-result">
                    <img src="../assets/shen.png" alt="">
                    <h3>审核中</h3>
                    <p class="result-title">您的直播计划将会在 1-3 个工作日内审核通过，请留意</p>
                </div>

                <!-- 步骤3：完成 -->
                <div v-if="step === 3" class="step-result">
                    <div class="result-icon">
                        <el-icon size="64" color="#52C41A">
                            <SuccessFilled />
                        </el-icon>
                    </div>
                    <h3>已完成</h3>
                    <p class="result-title">审核通过，可以进行开播了</p>
                </div>

                <!-- 底部按钮 -->
                <div class="drawer-footer">
                    <el-button v-if="step === 1" type="primary" @click="submit">下一步</el-button>
                    <el-button v-if="step === 2" type="primary" @click="submit">确定</el-button>
                    <el-button v-if="step === 3" type="primary" @click="closeAndRefresh">查看详情</el-button>
                </div>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, SuccessFilled } from '@element-plus/icons-vue'
import { create } from '@/api/plan'      // ← 新增：调后端接口
import { apiClient } from '@/utils/request'
/* ---------------- props & emit ---------------- */
const props = defineProps({ modelValue: Boolean })
const emit = defineEmits(['update:modelValue', 'success'])

/* ---------------- 基本状态 ---------------- */
const visible = ref(false)
const step = ref(1)
const formRef = ref()
const liveType = ref<'live' | 'vod'>('live')
const timeError = ref('')
const videoPreviewVisible = ref(false)

/* ---------------- 表单数据 ---------------- */
const form = ref({
    title: '',
    startTime: '',
    endTime: '',
    cover: '',
    desc: '',
    phone: '',
    wxQr: '',
    vodVideo: '',
    isHorizontal: true
})

/* ---------------- 校验规则 ---------------- */
const rules = {
    title: [
        { required: true, message: '请输入直播标题', trigger: 'blur' }
    ],
    startTime: [
        { required: true, message: '请选择开播时间', trigger: 'change' },
        {
            validator(_: any, value: string, cb: Function) {
                if (!value) return cb(new Error('请选择开播时间'))
                const selected = new Date(value)
                const now = new Date()
                const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)
                const sevenDaysLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)

                if (selected < oneHourLater) return cb(new Error('开播时间必须晚于当前时间1小时'))
                if (selected > sevenDaysLater) return cb(new Error('开播时间不能超过当前时间7天'))
                cb()
            },
            trigger: 'change'
        }
    ],
    endTime: [
        { required: true, message: '请选择开播时间', trigger: 'change' },
        {
            validator(_: any, value: string, cb: Function) {
                if (!value) return cb(new Error('请选择开播时间'))
                const selected = new Date(value)
                const now = new Date()
                const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)
                const sevenDaysLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)

                if (selected < oneHourLater) return cb(new Error('开播时间必须晚于当前时间1小时'))
                if (selected > sevenDaysLater) return cb(new Error('开播时间不能超过当前时间7天'))
                cb()
            },
            trigger: 'change'
        }
    ],
    cover: [
        { required: true, message: '请上传直播封面', trigger: 'change' }
    ],
    desc: [
        { required: true, message: '请输入直播介绍', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入电话号码', trigger: 'blur' }
    ],
    wxQr: [
        { required: true, message: '请上传企业微信客服二维码', trigger: 'change' }
    ],
    vodVideo: [
        {
            validator(_: any, __: any, cb: Function) {
                liveType.value === 'vod' && !form.value.vodVideo
                    ? cb(new Error('请上传点播视频'))
                    : cb()
            },
            trigger: 'change'
        }
    ]
}

/* ---------------- watch ---------------- */
watch(() => props.modelValue, val => (visible.value = val))
watch(visible, val => emit('update:modelValue', val))

/* ---------------- 工具函数 ---------------- */
const toggleLiveType = (type: 'live' | 'vod') => (liveType.value = type)

const disabledDate = (time: Date) => {
    const now = new Date()
    const sevenDaysLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
    const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)

    const sameDay = time.toDateString() === now.toDateString()
    if (sameDay) return time.getTime() < oneHourLater.getTime()
    return time.getTime() > sevenDaysLater.getTime()
}

const disabledTime = (date: Date) => {
    const now = new Date()
    const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000)
    const sameDay = date.toDateString() === now.toDateString()

    if (!sameDay) return {}
    return {
        hours: () => Array.from({ length: oneHourLater.getHours() }, (_, i) => i),
        minutes: (hour: number) =>
            hour === oneHourLater.getHours()
                ? Array.from({ length: oneHourLater.getMinutes() }, (_, i) => i)
                : []
    }
}
const uploadAvatar = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            form.value.cover = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
const beforeCoverUpload = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;

    // if (!file.type.startsWith('image/')) return ElMessage.error('请上传图片'), false
    // if (file.size / 1024 / 1024 > 2) return ElMessage.error('图片大小不超过 2M'), false
    // form.value.cover = URL.createObjectURL(file)
    // return false
}
// 二维码
const uploadAvatar3 = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            form.value.wxQr = res.data;
            ElMessage.success('头像上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
const beforeQrUpload = (rawFile: File) => {
    const isImage = rawFile.type.startsWith('image/');
    const isLt2M = rawFile.size / 1024 / 1024 < 2;
    if (!isImage) {
        ElMessage.error('请上传图片格式文件');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB');
    }
    return isImage && isLt2M;
}
// 视频
const uploadAvatar2 = async ({ file }: { file: File }) => {
    try {
        const fd = new FormData();
        fd.append('file', file);
        const res = await apiClient.post('/user/upload', fd, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
        if (res.code === 200) {
            form.value.vodVideo = res.data;
            ElMessage.success('上传成功');
        } else {
            ElMessage.error('上传失败');
        }
    } catch (e) {
        console.error(e);
        ElMessage.error('网络异常，上传失败');
    }
};
const beforeVodUpload = (rawFile: File) => {
    const isVideo = rawFile.type.startsWith('video/');
    if (!isVideo) {
        ElMessage.error('只能上传视频文件');
        return false;
    }

    const isLt10M = rawFile.size / 1024 / 1024 < 10;
    if (!isLt10M) {
        ElMessage.error('上传的视频大小不能超过10MB');
        return false;
    }

    return true;
}

/* ---------------- 关闭抽屉 ---------------- */
function handleClose(done: () => void) {
    if (step.value === 1 && checkFormDirty()) {
        ElMessageBox.confirm('表单数据未保存，确定要关闭吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            resetForm()
            done()
        })
    } else {
        resetForm()
        done()
    }
}

const checkFormDirty = () =>
    Object.values(form.value).some(v => v !== '' && v !== true)

const resetForm = () => {
    step.value = 1
    form.value = {
        title: '',
        startTime: '',
        endTime: '',
        cover: '',
        desc: '',
        phone: '',
        wxQr: '',
        vodVideo: '',
        isHorizontal: true
    }
    formRef.value?.resetFields()
    videoPreviewVisible.value = false
}

/* ---------------- 提交 ---------------- */
async function submit() {
    if (step.value === 1) {
        try {
            await formRef.value.validate()
            
        } catch {
            ElMessage.error('请完善表单信息')
        }
        // 调接口
        try {
            const payload = {
                livestreamTitle: form.value.title,
                livestreamStartTime: form.value.startTime,
                livestreamEndTime: form.value.endTime,
                livestreamIntroduce: form.value.desc,
                reservationCover: form.value.cover,
                liveType: liveType.value === 'live' ? 1 : 2,
                replayPublic: 0,
                reviewStatus: 1,               // 直接提交审核
                livestreamVideo: liveType.value === 'vod' ? form.value.vodVideo : '',
                livestreamStatus: 1,           // 待开播
                livestreamReservationNum: 0,
                userId: Number(localStorage.getItem('userId')),
                userName: localStorage.getItem('userName') || '',
                token: localStorage.getItem('token')
            }

            console.log(payload, 'payload====参数====')

            const { code, msg } = await create(payload)
            if (code === 200) {
                step.value = 3
                // 通知父组件把这条记录立即插入列表
                emit('success', {
                    title: form.value.title,
                    startTime: form.value.startTime,
                    endTime: form.value.endTime,
                    type: liveType.value === 'live' ? '人工直播' : '文件直播',
                    status: 'ready',
                    statusText: '待开播',
                    reserve: 0,
                    audit: 'pending',
                    auditText: '待审核',
                    link: ''
                })

                // 下一步
                step.value = 2
            } else {
                ElMessage.error(msg || '创建失败')
            }
        } catch (e) {
            ElMessage.error('创建直播失败，请稍后重试')
        }
    } else if (step.value === 2) {
        
    } else if (step.value === 3) {
        visible.value = false
    }
}

/* ---------------- 第三步按钮 ---------------- */
const closeAndRefresh = () => {
    visible.value = false
}
</script>

<style scoped>
.create-live-drawer {
    padding: 0 20px;
    height: 100%;
    position: relative;
    padding-bottom: 80px;
}

.step-form {
    margin-top: 40px;
}

.live-type-switch {
    display: flex;
    margin: 20px 0;
    border-radius: 4px;
    overflow: hidden;
    background-color: rgb(239,
            239,
            239);
    border: 1px solid #dcdfe6;
}

.switch-item {
    margin: 3px;
    padding: 10px 20px;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
    border-radius: 5px;
    color: #606266;
    transition: all 0.3s;
    width: 100px;
}

.switch-item:last-child {
    border-right: none;
}

.switch-item.active {
    background-color: #fff;
    font-weight: 700;
    width: 100px;
}

.switch-item:first-child.active {
    border-left: none;
}

.step-result {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 100px;
    text-align: center;
}

.cover-uploader,
.qr-uploader {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    overflow: hidden;
    cursor: pointer;
}

.cover,
.qr {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 6px;
}

.cover-placeholder,
.qr-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #999;
    font-size: 14px;
}

.live-type-switch {
    display: flex;
    margin: 20px 0;
    border-radius: 4px;
    overflow: hidden;
    background-color: rgb(239, 239, 239);
    border: 1px solid #dcdfe6;
}

.switch-item {
    flex: 1;
    padding: 10px 20px;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
    color: #606266;
}

.switch-item.active {
    background-color: #fff;
    font-weight: 700;
}

.result-icon {
    text-align: center;
    margin-bottom: 20px;
}

.result-title {
    font-size: 14px;
    color: #999999;
    text-align: center;
    margin-top: 10px;
}

.drawer-footer {
    position: absolute;

    right: 10px;
    display: flex;
    justify-content: flex-end;
}

:deep(.el-step__head.is-success) {
    color: #1677ff;
    border-color: #1677ff;
}

:deep(.el-step__title.is-success) {
    color: #1677ff;
}

.no-bg-dialog {
    background: transparent;
    box-shadow: none;
}
</style>